package com.sakiko.audiobook.album.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sakiko.audiobook.model.album.TrackInfo;
import com.sakiko.audiobook.query.album.TrackInfoQuery;
import com.sakiko.audiobook.vo.album.AlbumTrackListVo;
import com.sakiko.audiobook.vo.album.TrackListVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface TrackInfoMapper extends BaseMapper<TrackInfo> {

    /**
     * 分页查询用户声音列表
     *
     * @param trackListVoPage
     * @param trackInfoQuery
     * @return
     */
    IPage<TrackListVo> selectUserTrackPage(Page<TrackListVo> trackListVoPage, @Param("vo") TrackInfoQuery trackInfoQuery);

    /**
     * 维护 order_num 字段
     *
     * @param albumId
     * @param orderNum
     */
    @Update("update track_info set order_num = order_num -1 where album_id = #{albumId} and order_num > #{orderNum} and is_deleted = 0;")
    int updateOrderNum(@Param("albumId") Long albumId, @Param("orderNum") Integer orderNum);

    /**
     * 分页查询专辑声音列表
     *
     * @param trackListVoPage
     * @param albumId
     * @return
     */
    @Select("select track.id track_id,\n" +
            "       track.track_title,\n"+
            "       track.media_duration,\n" +
            "       track.order_num,\n" +
            "       max(case when stat.stat_type = '0701' then stat.stat_num else 0 end) as playStatNum,\n" +
            "       max(case when stat.stat_type = '0704' then stat.stat_num else 0 end) as commentStatNum,\n" +
            "       track.create_time\n" +
            "from track_info track\n" +
            "         inner join track_stat stat on track.id = stat.track_id\n" +
            "where track.status = '0501'\n" +
            "  and track.is_deleted = 0\n" +
            "  and track.album_id = #{albumId}\n" +
            "group by track.id")
    IPage<AlbumTrackListVo> selectAlbumTrackPage(Page<AlbumTrackListVo> trackListVoPage,@Param("albumId") Long albumId);
}
